#!/usr/bin/env python3
"""
简单的Java代码语法验证脚本
检查基本的语法错误，如括号匹配、分号等
"""

import os
import re
from pathlib import Path

def check_java_syntax(file_path):
    """检查Java文件的基本语法"""
    errors = []
    
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
            lines = content.split('\n')
        
        # 检查括号匹配
        brackets = {'(': ')', '[': ']', '{': '}'}
        stack = []
        
        for line_num, line in enumerate(lines, 1):
            # 移除字符串和注释中的括号
            line_clean = re.sub(r'"[^"]*"', '', line)  # 移除字符串
            line_clean = re.sub(r'//.*', '', line_clean)  # 移除单行注释
            
            for char in line_clean:
                if char in brackets:
                    stack.append((char, line_num))
                elif char in brackets.values():
                    if not stack:
                        errors.append(f"Line {line_num}: Unmatched closing bracket '{char}'")
                    else:
                        open_bracket, open_line = stack.pop()
                        if brackets[open_bracket] != char:
                            errors.append(f"Line {line_num}: Mismatched bracket. Expected '{brackets[open_bracket]}' but found '{char}'")
        
        # 检查未匹配的开括号
        for bracket, line_num in stack:
            errors.append(f"Line {line_num}: Unmatched opening bracket '{bracket}'")
        
        # 检查基本的Java语法模式
        for line_num, line in enumerate(lines, 1):
            line_stripped = line.strip()
            
            # 检查类声明
            if re.match(r'^\s*public\s+class\s+\w+', line):
                if not line.endswith('{') and not any('{' in lines[i].strip() for i in range(line_num, min(line_num + 3, len(lines)))):
                    errors.append(f"Line {line_num}: Class declaration should be followed by opening brace")
            
            # 检查方法声明
            if re.match(r'^\s*(public|private|protected).*\w+\s*\([^)]*\)\s*$', line):
                if not line.endswith('{') and not any('{' in lines[i].strip() for i in range(line_num, min(line_num + 3, len(lines)))):
                    errors.append(f"Line {line_num}: Method declaration should be followed by opening brace")
        
        return errors
        
    except Exception as e:
        return [f"Error reading file: {str(e)}"]

def main():
    """主函数"""
    java_files = []
    
    # 查找所有Java文件
    for root, dirs, files in os.walk('src'):
        for file in files:
            if file.endswith('.java'):
                java_files.append(os.path.join(root, file))
    
    print(f"Found {len(java_files)} Java files to check...")
    
    total_errors = 0
    files_with_errors = 0
    
    for java_file in java_files:
        errors = check_java_syntax(java_file)
        if errors:
            files_with_errors += 1
            total_errors += len(errors)
            print(f"\n❌ {java_file}:")
            for error in errors:
                print(f"  {error}")
        else:
            print(f"✅ {java_file}")
    
    print(f"\n📊 Summary:")
    print(f"  Total files checked: {len(java_files)}")
    print(f"  Files with errors: {files_with_errors}")
    print(f"  Total errors: {total_errors}")
    
    if total_errors == 0:
        print("🎉 All Java files passed basic syntax checks!")
        return 0
    else:
        print("⚠️  Some files have syntax issues that need to be fixed.")
        return 1

if __name__ == "__main__":
    exit(main())